using System;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;

namespace UnityXEditor
{
    [Serializable]
    public class AndroidToolSettings
    {
        private const string namespaceURI = @"http://schemas.android.com/apk/res/android";

        [SerializeField]
        private bool m_EnabledKeyPass = false;
        [SerializeField]
        private string m_KeystorePass = "";
        [SerializeField]
        private string m_KeyaliasPass = "";

        [SerializeField]
        private bool m_ConsumesOutsideTouches = false;

        [SerializeField]
        private bool m_SkipPermissionsDialog = false;

        [SerializeField]
        private bool m_ReadExternalStorage = false;
        [SerializeField]
        private bool m_WriteExternalStorage = false;
        [SerializeField]
        private bool m_ManageExternalStorage = false;
        [SerializeField]
        private bool m_LegacyExternalStorage = false;
        [SerializeField]
        private bool m_Vibrate = false;
        [SerializeField]
        private bool m_SMS = false;

#if UNITY_ANDROID
        //插件加载时
        [InitializeOnLoadMethod]
        private static void InitializeOnLoadMethod()
        {
            UnityXSettings.platformSettings.android.SetKeystorePassword();
        }
#endif
        public void OnGUI()
        {
            m_EnabledKeyPass = EditorGUILayout.Toggle("自动设置发布时证书密码", m_EnabledKeyPass);
            EditorGUI.indentLevel++;
            {
                EditorGUI.BeginDisabledGroup(!m_EnabledKeyPass);
                m_KeystorePass = EditorGUILayout.PasswordField("Keystore 密码", m_KeystorePass);
                m_KeyaliasPass = EditorGUILayout.PasswordField("Keyalias 密码", m_KeyaliasPass);
                EditorGUI.EndDisabledGroup();
            }
            EditorGUI.indentLevel--;

            EditorGUILayout.Space();
            m_ConsumesOutsideTouches = EditorGUILayout.Toggle("弹出屏幕键盘时在屏幕键盘区域之外禁用触摸", m_ConsumesOutsideTouches);

            EditorGUILayout.Space();
            m_SkipPermissionsDialog = EditorGUILayout.Toggle("禁用程序一启动就自动弹出所有权限对话框", m_SkipPermissionsDialog);
            EditorGUILayout.LabelField("添加权限");
            EditorGUI.indentLevel++;
            m_ReadExternalStorage = EditorGUILayout.Toggle("存储权限读", m_ReadExternalStorage);
            m_WriteExternalStorage = EditorGUILayout.Toggle("存储权限写", m_WriteExternalStorage);
            m_ManageExternalStorage = EditorGUILayout.Toggle("存储权限（安卓11以上版本）", m_ManageExternalStorage);
            m_LegacyExternalStorage = EditorGUILayout.Toggle("存储权限（安卓10以下版本或鸿蒙系统）", m_LegacyExternalStorage);
            m_Vibrate = EditorGUILayout.Toggle("手机震动权限", m_Vibrate);
            m_SMS = EditorGUILayout.Toggle("短信权限", m_SMS);
            EditorGUI.indentLevel--;
        }
        public void Update()
        {
            SetKeystorePassword();
            SetAndroidManifest();
            CodeFileTool.CommentsLine("AndroidTool.cs", "#define ENABLED_CONSUMES_OUTSIDE_TOUCHES", m_ConsumesOutsideTouches);
        }
        private void SetKeystorePassword()
        {
            if (!m_EnabledKeyPass)
                return;
            if (m_KeystorePass == null || m_KeystorePass.Length < 6)
                return;
            if (m_KeyaliasPass == null || m_KeyaliasPass.Length < 6)
                return;
            PlayerSettings.Android.keystorePass = m_KeystorePass;
            PlayerSettings.Android.keyaliasPass = m_KeyaliasPass;
        }
        private void SetAndroidManifest()
        {
            if (!File.Exists("Assets/Plugins/Android/AndroidManifest.xml"))
            {
                if (m_SkipPermissionsDialog
                    || m_ReadExternalStorage
                    || m_WriteExternalStorage
                    || m_ManageExternalStorage
                    || m_LegacyExternalStorage
                    || m_Vibrate
                    || m_SMS)
                {
                    Debug.LogError("请在ProjectSettings/Android里面勾选：“自定义主要清单”，否则自定义权限无法添加");
                    //string psfile  =  File.ReadAllText("ProjectSettings/ProjectSettings.asset");
                    //string newpsfile = Regex.Replace(psfile, @"useCustomMainManifest:[\s\S]*?[01]", "useCustomMainManifest: 1");
                    //File.WriteAllText("ProjectSettings/ProjectSettings.asset", newpsfile);
                    //AssetDatabase.Refresh();
                }
                return;
            }

            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load("Assets/Plugins/Android/AndroidManifest.xml");

            XmlElement manifest = xmlDocument.DocumentElement;
            XmlElement application = manifest["application"];
            XmlElement activity = application["activity"];

            EnabledElement(m_SkipPermissionsDialog, activity, "meta-data", "unityplayer.SkipPermissionsDialog", "true");
            EnabledAttribute(m_LegacyExternalStorage, application, "requestLegacyExternalStorage", "true");
            EnabledElement(m_ReadExternalStorage, manifest, "uses-permission", "android.permission.READ_EXTERNAL_STORAGE");
            EnabledElement(m_WriteExternalStorage, manifest, "uses-permission", "android.permission.WRITE_EXTERNAL_STORAGE");
            EnabledElement(m_ManageExternalStorage, manifest, "uses-permission", "android.permission.MANAGE_EXTERNAL_STORAGE");
            EnabledElement(m_Vibrate, manifest, "uses-permission", "android.permission.VIBRATE");
            EnabledElement(m_SMS, manifest, "uses-permission", "android.permission.READ_SMS");

            xmlDocument.Save("Assets/Plugins/Android/AndroidManifest.xml");
        }
        private void EnabledElement(bool enabled, XmlElement parentElement, string tagName, string name, string value = null)
        {
            if (enabled)
            {
                foreach (XmlNode item in parentElement.GetElementsByTagName(tagName))
                {
                    if ((item as XmlElement).GetAttribute("name", namespaceURI) == name)
                    {
                        return;
                    }
                }
                XmlElement xe = parentElement.OwnerDocument.CreateElement(tagName);
                xe.SetAttribute("name", namespaceURI, name);
                if (value != null)
                {
                    xe.SetAttribute("value", namespaceURI, value);
                }
                parentElement.AppendChild(xe);
            }
            else
            {
                foreach (XmlNode item in parentElement.GetElementsByTagName(tagName))
                {
                    if ((item as XmlElement).GetAttribute("name", namespaceURI) == name)
                    {
                        parentElement.RemoveChild(item);
                        return;
                    }
                }
            }
        }
        private void EnabledAttribute(bool enabled, XmlElement element, string attributeName, string attributeValue)
        {
            if (enabled)
            {
                element.SetAttribute(attributeName, namespaceURI, attributeValue);
            }
            else
            {
                element.RemoveAttributeNode(attributeName, namespaceURI);
            }
        }
    }
}
